package com.qixin.modules.ea.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.qixin.modules.ea.entity.*;
import com.qixin.modules.ea.mapper.EaEntertainMapper;
import com.qixin.modules.ea.mapper.EaTravelMapper;
import com.qixin.modules.ea.vo.EaEntertainPrintVo;
import com.qixin.modules.eaApplication.entity.EaEntertainApply;
import com.qixin.modules.eaApplication.service.IEaEntertainApplyService;
import com.qixin.modules.eaApplication.service.impl.EaEntertainApplyServiceImpl;
import com.qixin.modules.eaBasic.entity.EaTask;
import com.qixin.modules.rzInvoice.entity.EaBill;
import com.qixin.modules.rzInvoice.service.impl.EaBillServiceImpl;
import com.qixin.utils.PreciseCompute;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.ConvertUpMoneyUtil;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.activiti.entity.ActZTask;
import org.jeecg.modules.activiti.mapper.ActZTaskMapper;
import org.jeecg.modules.activity.service.ActivityCommonService;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.qixin.modules.ea.vo.EaEntertainPage;
import com.qixin.modules.ea.service.IEaEntertainService;
import com.qixin.modules.ea.service.IEaBookDetailService;
import com.qixin.modules.ea.service.IEaApplyDetailService;
import com.qixin.modules.ea.service.IEaEntertainReceptionActivityService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ea_entertain
 * @Author: qixin-boot
 * @Date: 2022-01-21
 * @Version: V1.0
 */
@Api(tags = "招待费报销单")
@RestController
@RequestMapping("/ea/eaEntertain")
@Slf4j
public class EaEntertainController {
    @Autowired
    private IEaEntertainService eaEntertainService;
    @Autowired
    private IEaBookDetailService eaBookDetailService;
    @Autowired
    private IEaApplyDetailService eaApplyDetailService;
    @Autowired
    private IEaEntertainReceptionActivityService eaEntertainReceptionActivityService;
    @Autowired
    private INcPersonnelService ncPersonnelService;
    // 工作流公共执行类
    @Autowired
    private ActivityCommonService activityCommonService;
    @Autowired
    private IEaEntertainApplyService eaEntertainApplyService;
    @Autowired
    private EaBillServiceImpl eaBillService;
    @Autowired
    private ActZTaskMapper actZTaskMapper;
    @Autowired
    private EaEntertainMapper eaEntertainMapper;

    /**
     * 分页列表查询
     *
     * @param eaEntertain
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "招待费报销单-分页列表查询", notes = "招待费报销单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(EaEntertain eaEntertain,
                                   @RequestParam(name = "billDateBegin", required = false) String billDateBegin,
                                   @RequestParam(name = "billDateEnd", required = false) String billDateEnd,
                                   @RequestParam(name="billCode", required = false) String billCode,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<EaEntertain> queryWrapper = QueryGenerator.initQueryWrapper(eaEntertain, req.getParameterMap());
        //add-begin-by wujinbiao for 添加查询条件 列表排序，创建人
        if (StringUtils.isNotBlank(billDateBegin)) {
            queryWrapper.ge("bill_date", billDateBegin);
        }
        if (StringUtils.isNotBlank(billDateEnd)) {
            queryWrapper.le("bill_date", billDateEnd);
        }
        if(StringUtils.isNotBlank(billCode)){
            // 单据编号模糊查询
            queryWrapper.like("bill_no",billCode);
        }
        queryWrapper.orderByDesc("create_time");
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.and(
                wrapper -> wrapper.eq("create_by",loginUser.getId()).or().eq("person_id",loginUser.getPkPsndoc())
        );
        //add-end-by wujinbiao for 添加查询条件
        queryWrapper.orderByDesc("create_time");
        Page<EaEntertain> page = new Page<EaEntertain>(pageNo, pageSize);
        IPage<EaEntertain> pageList = eaEntertainService.page(page, queryWrapper);
        List<EaEntertain> records = pageList.getRecords();
        for (EaEntertain eaEntertain1 : records) {
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaEntertain1.getPersonId());
            if (ncPersonnel != null) {
                eaEntertain1.setPersonIdName(ncPersonnel.getName());
            }
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param eaEntertainPage
     * @return
     */
    @AutoLog(value = "招待费报销单-添加")
    @ApiOperation(value = "招待费报销单-添加", notes = "招待费报销单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody EaEntertainPage eaEntertainPage) {
        EaEntertain eaEntertain = new EaEntertain();
        BeanUtils.copyProperties(eaEntertainPage, eaEntertain);

        // update-begin-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("prefix","ZDBX"); // 编码前缀
        Object result = FillRuleUtil.executeRule("common_code", jsonObj);
        eaEntertain.setBillNo(result.toString());
        // update-end-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        eaEntertain.setState(0);
        eaEntertainService.saveMain(eaEntertain, eaEntertainPage.getEaBookDetailList(), eaEntertainPage.getEaApplyDetailList(), eaEntertainPage.getEaEntertainReceptionActivities());
        //add-begin-by 2022-02-07 wjb for 返回主表、子表数据给前端
        EaEntertainPage resultPage = new EaEntertainPage();
        BeanUtils.copyProperties(eaEntertain, resultPage);
        resultPage.setEaEntertainReceptionActivities(eaEntertainPage.getEaEntertainReceptionActivities());
        resultPage.setEaBookDetailList(eaEntertainPage.getEaBookDetailList());
//      resultPage.setEaApplyDetailList(eaEntertainPage.getEaApplyDetailList());
        //add-end-by 2022-02-07 wjb for 返回主表、子表数据给前端

        //update-begin-author wjb 2022-02-10 15:49 返回关联的申请单实体集合
        QueryWrapper<EaEntertainApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ea_entertain_id",eaEntertain.getId());
        EaEntertainApply eaEntertainApply = eaEntertainApplyService.getOne(queryWrapper);
        ArrayList<EaEntertainApply> eaEntertainApplyList = new ArrayList<>();
        eaEntertainApplyList.add(eaEntertainApply);
        resultPage.setEaApplyDetailList(eaEntertainApplyList);
        //update-end-author wjb 2022-02-10 15:49 返回关联的申请单实体集合

        return Result.OK(resultPage);
    }

    /**
     * 编辑
     *
     * @param eaEntertainPage
     * @return
     */
    @AutoLog(value = "招待费报销单-编辑")
    @ApiOperation(value = "招待费报销单-编辑", notes = "招待费报销单-编辑")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody EaEntertainPage eaEntertainPage) {
        EaEntertain eaEntertain = new EaEntertain();
        BeanUtils.copyProperties(eaEntertainPage, eaEntertain);
        EaEntertain eaEntertainEntity = eaEntertainService.getById(eaEntertain.getId());
        if (eaEntertainEntity == null) {
            return Result.error("未找到对应数据");
        }
        eaEntertain.setSaveType("add");
        eaEntertainService.updateMain(eaEntertain, eaEntertainPage.getEaBookDetailList(), eaEntertainPage.getEaApplyDetailList(), eaEntertainPage.getEaEntertainReceptionActivities());
        //add-begin-by 2022-02-07 wjb for 返回主表、子表数据给前端
        EaEntertainPage resultPage = new EaEntertainPage();
        BeanUtils.copyProperties(eaEntertain, resultPage);
        resultPage.setEaEntertainReceptionActivities(eaEntertainPage.getEaEntertainReceptionActivities());
//        resultPage.setEaApplyDetailList(eaEntertainPage.getEaApplyDetailList());
        resultPage.setEaBookDetailList(eaEntertainPage.getEaBookDetailList());
        //add-end-by 2022-02-07 wjb for 返回主表、子表数据给前端

        //update-begin-author wjb 2022-02-10 15:49 返回关联的申请单实体集合
        QueryWrapper<EaEntertainApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ea_entertain_id",eaEntertain.getId());
        EaEntertainApply eaEntertainApply = eaEntertainApplyService.getOne(queryWrapper);
        ArrayList<EaEntertainApply> eaEntertainApplyList = new ArrayList<>();
        eaEntertainApplyList.add(eaEntertainApply);
        resultPage.setEaApplyDetailList(eaEntertainApplyList);
        //update-end-author wjb 2022-02-10 15:49 返回关联的申请单实体集合

        return Result.OK(resultPage);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "招待费报销单-通过id删除")
    @ApiOperation(value = "招待费报销单-通过id删除", notes = "招待费报销单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        QueryWrapper<EaEntertain> params = new QueryWrapper<>();
        params.eq("id",id);
        EaEntertain entertain = eaEntertainService.getOne(params);
        if(entertain != null && entertain.getState() > 0){
            return Result.error("该单据已发起流程,不可删除!");
        }
        eaEntertainService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "招待费报销单-批量删除")
    @ApiOperation(value = "招待费报销单-批量删除", notes = "招待费报销单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.eaEntertainService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "招待费报销单-通过id查询", notes = "招待费报销单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        EaEntertainPage resultPage = new EaEntertainPage();
        EaEntertain eaEntertain = eaEntertainService.getById(id);
        if (eaEntertain == null) {
            return Result.error("未找到对应数据");
        }

        String personIdName = "";
        //add-begin-by wjb for 报销人中文返回 子表数据
        //查询报销人中文
        if (StringUtils.isNotBlank(eaEntertain.getPersonId())) {
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaEntertain.getPersonId());
            if (ncPersonnel != null) {
                personIdName = ncPersonnel.getName();
                eaEntertain.setPersonIdName(personIdName);
            }
        }
        //如果报销人和收款人是同一个人，直接返回报销人中文给收款人
//		if(StringUtils.isNotBlank(eaEntertain.getRecPersonId()) && eaEntertain.getRecPersonId().equals(eaEntertain.getPersonId())){
//			eaEntertain.setRecPersonIdName(personIdName);
//		}else {
//			NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaEntertain.getRecPersonId());
//			eaEntertain.setRecPersonIdName(ncPersonnel.getName());
//		}
        BeanUtils.copyProperties(eaEntertain, resultPage);
        List<EaBookDetail> eaBookDetails = eaBookDetailService.selectByMainId(eaEntertain.getId());
        List<EaApplyDetail> eaApplyDetails = eaApplyDetailService.selectByMainId(eaEntertain.getId());
        List<EaEntertainReceptionActivity> eaEntertainReceptionActivities = eaEntertainReceptionActivityService.selectByMainId(eaEntertain.getId());
        resultPage.setEaBookDetailList(eaBookDetails);
//        eaEntertainPage.setEaApplyDetailList(eaApplyDetails);
        resultPage.setEaEntertainReceptionActivities(eaEntertainReceptionActivities);
        //add-end-by wjb for 报销人中文返回 子表数据
        //update-begin-author wjb 2022-02-10 15:49 返回关联的申请单实体集合
        QueryWrapper<EaEntertainApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ea_entertain_id",eaEntertain.getId());
        EaEntertainApply eaEntertainApply = eaEntertainApplyService.getOne(queryWrapper);
        ArrayList<EaEntertainApply> eaEntertainApplyList = new ArrayList<>();
        eaEntertainApplyList.add(eaEntertainApply);
        resultPage.setEaApplyDetailList(eaEntertainApplyList);
        //update-end-author wjb 2022-02-10 15:49 返回关联的申请单实体集合

        return Result.OK(resultPage);
    }

    /**
     * @param id
     * @return
     * @Description 招待费报销单打印模板-通过id查询
     * @author wujinbiao
     * @date 2022/2/8
     */
    @ApiOperation(value = "招待费报销单打印模板-通过id查询", notes = "招待费报销单打印模板-通过id查询")
    @GetMapping(value = "/selectById")
    public Result<?> selectById(@RequestParam(name = "id", required = true) String id) {
        EaEntertain eaEntertain = eaEntertainService.getById(id);
        if (eaEntertain == null) {
            return Result.error("未找到对应数据");
        }
        EaEntertainPrintVo eaEntertainPrintVo = new EaEntertainPrintVo();
        BeanUtils.copyProperties(eaEntertain,eaEntertainPrintVo);

        if (StringUtils.isNotBlank(eaEntertain.getRecPersonId())) {
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaEntertain.getRecPersonId());
            if (ncPersonnel != null) {
                eaEntertainPrintVo.setRecPersonIdName(ncPersonnel.getName());
            }
        }

        eaEntertainPrintVo.setTzrq(eaEntertain.getBillDate());

        //将实际付款金额转为大写金额
        String actualPayAmt = eaEntertain.getActualPayAmt() != null ? eaEntertain.getActualPayAmt().toString() : "0";
        actualPayAmt = ConvertUpMoneyUtil.toChinese(actualPayAmt);
        eaEntertainPrintVo.setActualPayAmt_cn(actualPayAmt);

        //将住宿情况_费用总计转为大写金额
        String accommodationAmt_cn = eaEntertain.getAccommodationAmt() != null ? eaEntertain.getAccommodationAmt().toString() : "0";
        accommodationAmt_cn = ConvertUpMoneyUtil.toChinese(accommodationAmt_cn);
        eaEntertainPrintVo.setAccommodationAmt_cn(accommodationAmt_cn);

        //将用餐安排_费用总计转为大写金额
        String mealArrangementAmt_cn = eaEntertain.getMealArrangementAmt() != null ? eaEntertain.getMealArrangementAmt().toString() : "0";
        mealArrangementAmt_cn = ConvertUpMoneyUtil.toChinese(mealArrangementAmt_cn);
        eaEntertainPrintVo.setMealArrangementAmt_cn(mealArrangementAmt_cn);

        // update-begin-by wujinbiao 2022/3/17 14:34 for
        //将用餐安排_酒水明细（含酒水售价）转为大写金额
        String mealArrangementWineDetail_cn = eaEntertain.getMealArrangementWineDetail();
        eaEntertainPrintVo.setMealArrangementWineDetail_cn(mealArrangementWineDetail_cn);
        // update-end-by wujinbiao 2022/3/17 14:34 for

        // update-begin-by wujinbiao 2022/3/8 8:43 for 添加活动内容信息返回
        if(StringUtils.isNotBlank(id)){
            List<EaEntertainReceptionActivity> eaEntertainReceptionActivities = eaEntertainReceptionActivityService.selectByMainId(id);
            eaEntertainPrintVo.setEaEntertainReceptionActivities(eaEntertainReceptionActivities);
        }
        // update-end-by wujinbiao 2022/3/8 8:43 for 添加活动内容信息返回

        //审批流程
        // update-begin-Autor: wjb date: 2022-02-10 14:50 for: 添加流程审批记录
        if (StringUtils.isNotBlank(eaEntertain.getProcInstId())){
            List<Map<String, Object>> nodeList = activityCommonService.getNodeList(eaEntertain.getProcInstId());
            eaEntertainPrintVo.setSpjl(nodeList);
        }
        // update-end-Autor: wjb date: 2022-02-10 14:50 for: 添加流程审批记录

        return Result.OK(eaEntertainPrintVo);
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "费用明细-主表ID查询", notes = "费用明细-通主表ID查询")
    @GetMapping(value = "/queryEaBookDetailByMainId")
    public Result<?> queryEaBookDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<EaBookDetail> eaBookDetailList = eaBookDetailService.selectByMainId(id);
        return Result.OK(eaBookDetailList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "申请单明细-主表ID查询", notes = "申请单明细-通主表ID查询")
    @GetMapping(value = "/queryEaApplyDetailByMainId")
    public Result<?> queryEaApplyDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<EaApplyDetail> eaApplyDetailList = eaApplyDetailService.selectByMainId(id);
        return Result.OK(eaApplyDetailList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "活动内容-通过主表ID查询", notes = "活动内容-通过主表ID查询")
    @GetMapping(value = "/queryEaEntertainReceptionActivityByMainId")
    public Result<?> queryEaEntertainReceptionActivityListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<EaEntertainReceptionActivity> eaEntertainReceptionActivityList = eaEntertainReceptionActivityService.selectByMainId(id);
        return Result.OK(eaEntertainReceptionActivityList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param eaEntertain
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EaEntertain eaEntertain) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<EaEntertain> queryWrapper = QueryGenerator.initQueryWrapper(eaEntertain, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<EaEntertain> queryList = eaEntertainService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<EaEntertain> eaEntertainList = new ArrayList<EaEntertain>();
        if (oConvertUtils.isEmpty(selections)) {
            eaEntertainList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            eaEntertainList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<EaEntertainPage> pageList = new ArrayList<EaEntertainPage>();
        for (EaEntertain main : eaEntertainList) {
            EaEntertainPage vo = new EaEntertainPage();
            BeanUtils.copyProperties(main, vo);
            List<EaBookDetail> eaBookDetailList = eaBookDetailService.selectByMainId(main.getId());
            vo.setEaBookDetailList(eaBookDetailList);
            List<EaApplyDetail> eaApplyDetailList = eaApplyDetailService.selectByMainId(main.getId());
//            vo.setEaApplyDetailList(eaApplyDetailList);
            List<EaEntertainReceptionActivity> eaEntertainReceptionActivityList = eaEntertainReceptionActivityService.selectByMainId(main.getId());
            vo.setEaEntertainReceptionActivities(eaEntertainReceptionActivityList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "ea_entertain列表");
        mv.addObject(NormalExcelConstants.CLASS, EaEntertainPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("ea_entertain数据", "导出人:" + sysUser.getRealname(), "ea_entertain"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<EaEntertainPage> list = ExcelImportUtil.importExcel(file.getInputStream(), EaEntertainPage.class, params);
                for (EaEntertainPage page : list) {
                    EaEntertain po = new EaEntertain();
                    BeanUtils.copyProperties(page, po);
                    eaEntertainService.saveMain(po, page.getEaBookDetailList(), page.getEaApplyDetailList(), page.getEaEntertainReceptionActivities());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * 发票更新
     *
     * @param billIds
     * @return
     */
    @AutoLog(value = "发票更新")
    @ApiOperation(value = "发票更新", notes = "发票更新")
    @PutMapping(value = "/updeteFpState")
    @Transactional
    public Result<?> updeteFpState(@RequestParam(name = "billIds", required = true) String billIds) {
        if (!org.apache.commons.lang.StringUtils.isEmpty(billIds)) {
            String[] ids = billIds.split(",");
            // 发票金额
            double amount = 0;
            // 实际付款金额
            double actualEaAmt = 0;
            // 业务表id
            String billId = "";
            List<EaBookDetail> eaBookDetails = new ArrayList<>();
            List<EaBill> eaBills = new ArrayList<>();
            for (String id : ids) {
                // 需要更新的发票明细行数据
                EaBookDetail eaBookDetail = eaBookDetailService.selectById(id);
                if(eaBookDetail == null || "".equals(eaBookDetail)){
                    return Result.error("找不到对应数据");
                }
                // 需要更新的发票数据
                EaBill eaBill = eaBillService.getById(eaBookDetail.getFpid());
                billId = eaBookDetail.getBillId();
                // 发票被引用
                if ("1".equals(eaBill.getIsused()) && eaBookDetail.getBillId() != null) {
                    amount = PreciseCompute.add(amount,eaBookDetail.getAmount().doubleValue());
                    actualEaAmt = PreciseCompute.add(actualEaAmt,eaBookDetail.getActualEaAmt().doubleValue());
                    // 关联的表单id置为空
                    eaBookDetail.setBillId("");
                    // 发票状态更新
                    eaBill.setIsused("0");

                    eaBookDetails.add(eaBookDetail);
                    eaBills.add(eaBill);
                }
            }
            // 取消费用明细行和业务表单的关系
            eaBookDetailService.updateBatchById(eaBookDetails);
            // 修改发票已报销状态
            eaBillService.updateBatchById(eaBills);

            // 报销单减去实际付款金额、报销金额
            if (billId != ""){
                EaEntertain eaEntertain =  eaEntertainMapper.selectById(billId);

                // 修改待办列表的还款金额
                Map<String, Object> params = new HashMap<>();
                params.put("table_id",billId);
                List<ActZTask> actZTasks = actZTaskMapper.selectByMap(params);
                if(actZTasks.size() > 0){
                    // 修改任务列表 对应的报销金额
                    ActZTask actZTask = actZTasks.get(0);
                    actZTask.setTotalFee(new BigDecimal(PreciseCompute.sub(eaEntertain.getEaAmt().doubleValue(),amount)));
                    actZTaskMapper.updateById(actZTask);
                }
                // 报销金额 修改
                eaEntertain.setEaAmt(new BigDecimal(PreciseCompute.sub(eaEntertain.getEaAmt().doubleValue(),amount)));
                // 实际付款金额 修改
                eaEntertain.setActualPayAmt(new BigDecimal(PreciseCompute.sub(eaEntertain.getActualPayAmt().doubleValue(),actualEaAmt)));
                eaEntertainService.updateById(eaEntertain);
            }
        }

        return Result.OK();
    }


}
